print("-------------------------\r\nESP8266_Lua_DeskClockDht11 \r\n-------------------------")
--[[ nodeMCU --- ESP8266 IO map
0--GPIO16   1--GPIO5   2--GPIO4   3--GPIO0   4--GPIO2
5--GPIO14   6--GPIO12  7--GPIO13  8--GPIO15  9--GPIO3
10--GPIO1   11--GPIO9  12--GPIO10
]]

-----------------------------wifi------------------------------
wifi.setmode(wifi.STATIONAP)
--wifi.ap.config({ssid="ESP8266", auth=wifi.OPEN})
--enduser_setup.manual(true)
enduser_setup.start(
  function()
    print("enduser_setup Connected to WiFi as:" .. wifi.sta.getip())
  end,
  function(err, str)
    print("enduser_setup: Err #" .. err .. ": " .. str)
  end
)

--[[
configwifissid = "ChinaNet-PEtw";
configwifipwd="d9aprfdw";
wifi.setmode(wifi.STATIONAP)
apcfg={}
apcfg.ssid=configwifissid
apcfg.pwd=configwifipwd
wifi.sta.config(apcfg)
wifi.sta.autoconnect(1)
]]
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
    print("eventmon.STA_DISCONNECTED")
    disp:clearBuffer()
    disp:drawFrame(0, 0, 128, 64)
    disp:drawStr(12, 4, "DeskClock")
    disp:drawLine(8, 20, 120, 20)
    disp:drawStr(4, 32, "Wifi connect...")
    disp:sendBuffer()
end)

wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    print("eventmon.STA_GOT_IP IP: "..T.IP)
    disp:clearBuffer()
    disp:drawFrame(0, 0, 128, 64)
    disp:drawStr(4, 32,T.IP)
    disp:sendBuffer()
end)

------------------------------------OLED----------------------------
function init_oled()
    local sda = 2
    local scl = 5
    local sla = 0x3c

    i2c.setup(0, sda, scl, i2c.SLOW)
    disp = u8g2.ssd1306_i2c_128x64_noname(0, sla)
    disp:setFlipMode(1)
    disp:setFont(u8g2.font_unifont_t_symbols)
    disp:setFontRefHeightExtendedText()
    --disp:setDrawColor(1)
    disp:setFontPosTop()
    --disp:setFontDirection(0)

    disp:clearBuffer()
    disp:drawFrame(0, 0, 128, 64)
    disp:drawStr(48, 4, "JYTK")
    disp:drawLine(8, 20, 120, 20)
    disp:drawStr(4, 32, "Wifi connect...")
    disp:sendBuffer()
end

init_oled()

--------------------------------------OLED_SHOW-----------------------------------
local current_day = "2022-01-01"
local current_time = "00:00:00"
local dht11_temperaure = "00.0"
local dht11_hum = "00.0"
--font_unifont_t_symbols,font_timB24_tf,font_freedoomr25_mn
local disp_clear = 1
function oled_show()
    --print(current_day.."  "..current_time.."  "..dht11_temperaure.."  "..dht11_hum)
    if (wifi.sta.getip() ~= nil) then

        if (string.sub(current_time, -2, -1) == "00") then
            first_clear = 1
        end
     
        if (get_ntp_update_flag() == 1) then
            --[[if(disp_clear == 1)then
                disp:clearBuffer()
                disp_clear = 0
            end]]
            disp:clearBuffer()
            disp:setFont(u8g2.font_unifont_t_symbols)
            disp:drawStr(0, 0,  " DAY "..current_day)
            disp:drawStr(4, 50, "T: "..dht11_temperaure.."C".."   ".."H: "..dht11_hum .. "%")
            disp:drawLine(5, 16, 123, 16)
            disp:drawLine(5, 47, 123, 47)
            disp:drawLine(64, 47, 64, 64)
            disp:setFont(u8g2.font_timB24_tf)
            disp:drawStr(5, 20, current_time)
            disp:sendBuffer()
        end
    end
end
local oled_show_time = tmr.create()
oled_show_time:alarm(1000, tmr.ALARM_AUTO, oled_show)

-------------------------------NTP------------------------------------------
local NTP_SERVERS = { "ntp.aliyun.com",
                "time.asia.apple.com",
                "cn.ntp.org.cn",
                "time.windows.com",
                "cn.pool.ntp.org"
                }
local ntp_update_flag = 0

local function StpSync_OK(sec, usec, server, info)
    print('StpSync_OK', sec, usec, server)
    Timer_SyncNTP:interval(3600000)
    printTime()
    ntp_update_flag = 1
end

local function StpSync_Fail()
    print('StpSync_Fail')
end

local function NtpSync()
    if (wifi.sta.getip() == nil) then
        print("NtpSync wifi Connecting...")
    else
        print("NtpSync wifi Connected, IP is "..wifi.sta.getip())
        sntp.sync(NTP_SERVERS, StpSync_OK, StpSync_Fail)
    end
end

function get_ntp_update_flag()
    return ntp_update_flag
end

function printTime()
    tm = rtctime.epoch2cal(rtctime.get() + 8 * 3600)
    print(string.format("%04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"]))
    current_day = string.format("%04d/%02d/%02d", tm["year"], tm["mon"], tm["day"])
    current_time = string.format("%02d:%02d:%02d", tm["hour"], tm["min"], tm["sec"])
end

Timer_SyncNTP = tmr.create()
Timer_SyncNTP:register(10000, tmr.ALARM_AUTO, NtpSync)
Timer_SyncNTP:start()

Timer_Print = tmr.create()
Timer_Print:register(1000, tmr.ALARM_AUTO, printTime)
Timer_Print:start()

-----------------------------------dht11----------------------------
local DHT11pin     = 1  -- D1, GPIO5
local DHT11Temp    = 0
local DHT11TempDec = 0
local DHT11Hum     = 0
local DHT11HumDec  = 0
local ErrChk       = true
local ErrTimeOut   = true
local DHT11Status  = dht.ERROR_TIMEOUT

local function getDHT11Info()
    DHT11Status, DHT11Temp, DHT11Hum, DHT11TempDec, DHT11HumDec = dht.read11(DHT11pin)
    if DHT11Status == dht.OK then
        ErrChk     = false;
        ErrTimeOut = false;     
        print(string.format("DHT Temperature:%d.%02d;  Humidity:%d.%02d\r\n",
              DHT11Temp,
              DHT11TempDec,
              DHT11Hum,
              DHT11HumDec))

        dht11_temperaure = DHT11Temp
        dht11_hum = DHT11Hum
    elseif DHT11Status == dht.ERROR_CHECKSUM then
        ErrChk = true
        print( "DHT Checksum error." )
    elseif DHT11Status == dht.ERROR_TIMEOUT then
        ErrTimeOut = true
        print( "DHT TimeOut." )
    end
end

local dht_timer = tmr.create()
dht_timer:alarm(1000, tmr.ALARM_AUTO,getDHT11Info)

function get_dht11_update_flag()
    if not(ErrChk or ErrTimeOut) then
        return 1
    else
        return 0
    end
end
